<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏中</title>
    <link rel="stylesheet" href="../static/css/main.css">
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            width: 100%;
            height: 100%;
            background: url('/static/login_background.jpg') no-repeat;
            background-size: cover;
        }

        .replay,
        .exit,
        .mode,
        .SpeechRecognition,
        .reBack,
        .pass {
            margin-top: .5625rem;
            margin-right: .5625rem;
            width: 8%;
            height: 1.2625rem;
            border-radius: .3125rem;
            border: 0;
            color: #fff;
            text-align: center;
            line-height: .9375rem;
            font-size: .4688rem;
            background-image: linear-gradient(to right, #30cfd0, #330867);
        }

        #btn {
            text-shadow: -1px 1px 1px rgb(30, 53, 100),
                -1px 1px 1px rgb(30, 53, 100),
                -1px 1px 1px rgb(30, 53, 100),
                -1px 1px 1px rgb(30, 53, 100),
                -1px 1px 1px rgb(30, 53, 100),
                -1px 1px 1px rgb(30, 53, 100);
            box-shadow: 0px 5px 0px 0px rgb(35, 35, 86);
            transition: all .5s;
        }


        #btn:active {
            transform: translate(0, 4px);
            box-shadow: 0px 2px 0px 0px rgb(30, 53, 100);
        }




        .rules {
            box-sizing: border-box;
            margin-top: 20px;
            margin-left: 50px;
            width: 300px;
            height: 400px;
            background-color: rgba(255, 255, 255, .5);
            position: fixed;
            padding-left: 6px;
            padding-right: 6px;
            font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif
        }
    </style>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
    <script>
        document.addEventListener('visibilitychange', () => {
            const state = document.visibilityState
            if(state == "hidden"){
                document.getElementsByTagName("title")[0].innerText = '快回来继续下棋！';	
            }
            else{
                document.getElementsByTagName("title")[0].innerText = '游戏中！';	
            }
            // console.log(state) // hidden 表示当前页面切换为隐藏状态，visible表示当前页面切换为浏览状态
        })

    </script>
</head>

<body>
    <div id="title" style="margin-top: 20px;text-align: center;color: aliceblue;">
        <h1>五子棋</h1>
        <h6>双人模式</h6>
        <button id="btn" class="replay" onclick="replay()">重新开始</button>
        <button id="btn" class="mode" onclick="selectMode()">返回游戏模式</button>
        <button id="btn" class="exit" onclick="exit()">退出登录</button>
        <input id="btn" type="button" class="SpeechRecognition" onclick="Recognation(this)" value="语音识别"></button>
        <button id="btn" class="reBack" onclick="saveMode()">保存本局记录</button>
        <button id="btn" class="reBack" onclick="ifReturn()">回滚上局记录</button>
        <button id="btn" class="pass" onclick="pass()">PASS</button>
    </div>
    <div class="rules">
        <h1 style="margin-bottom: 5px;">游戏规则</h1>
        <p>&nbsp;&nbsp;(1)对局双方各执一色棋子。</p>
        <p>&nbsp;&nbsp;(2)空棋盘开局。</p>
        <p>&nbsp;&nbsp;(3)黑先、白后，交替下子，每次只能下一子。</p>
        <p>&nbsp;&nbsp;(4)棋子下在棋盘的空白点上，棋子下定后，不得向其它点移动，不得从棋盘上拿掉或拿起另落别处。</p>
        <p>&nbsp;&nbsp;(5)黑方的第一枚棋子可下在棋盘任意交叉点上。</p>
        <p>&nbsp;&nbsp;(6)轮流下子是双方的权利，但允许任何一方放弃下子权（即：PASS权）</p>
        <p>&nbsp;&nbsp;(7)如使用语音控制模式，可点击语音识别按钮，然后通过麦克风录入普通话语音，等待片刻即可控制棋子落下。</p>
        <p>&nbsp;&nbsp;录入语音格式为第XX行第XX列，否则会识别失败</p>
    </div>
    <!--canvas是个画布，需要修改的是尺寸，不是修改样式-->
    <canvas id="canvas" width="600" height="600" style="background-color:rgba(255, 255, 255, .5);"
        onclick="playChess(event)"></canvas>

    <div class="mol-main">
        <div class="mol-header">
            <h2 style="width: 100%;text-align: center;">五子棋小游戏</h2>
        </div>
        <div class="mol-success white" style="width: 100%;text-align: center;">
            白棋获胜
        </div>
        <div class="mol-success black" style="width: 100%;text-align: center;">
            黑棋获胜
        </div>
        <br>
        <div>
            <button class="btn" style="width: 100%;text-align: center;">关闭</button>
        </div>
    </div>
</body>

<script>
    function pass() {
        isBlack ^= 1;
    }
    function ifReturn() {
        var flag = confirm("是否恢复上局记录")
        if (!flag) {
            return
        }
        else {
            $.ajax({
                url: '/returnPre',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    if (data.code == 200) {
                        console.log(typeof (data.msg))
                        var mpp = eval(data.msg)
                        var num_b = 0
                        var num_w = 0
                        for (var i = 0; i < 20; i++) {
                            for (var j = 0; j < 20; j++) {
                                col = j;
                                row = i;
                                if (mpp[i][j] < 1) continue;
                                if (map[row][col]) {
                                    alert("此处已被落子");
                                    return;
                                }
                                isBlack = mpp[i][j] > 1 ? 1 : 0
                                if (isBlack) num_b++;
                                else num_w++;
                                drawChess(col * 30, row * 30, colorBox[isBlack]);
                                map[row][col] = 1;
                                $.ajax({
                                    url: "/check",
                                    type: 'post',
                                    dataType: 'json',
                                    data: {
                                        flag: isBlack,
                                        row: row,
                                        col: col,
                                    },
                                    success: function (data) {
                                        // console.log(data)
                                        if (data.code == 201) {
                                            $('.mol-main').css('display', 'block');
                                            $('.black').css('display', 'block');
                                        }
                                        else if (data.code == 202) {
                                            $('.mol-main').css('display', 'block');
                                            $('.white').css('display', 'block');
                                        }
                                    },
                                    error: function (error) {
                                        // console.log(error)
                                    }
                                })
                            }
                        }
                        if (num_b == num_w) isBlack = 1
                        else isBlack = 0
                        alert("回滚成功")
                    }
                    else {
                        alert("回滚失败，请重试！！！")
                    }
                },
                error: function (error) {
                    console.log(error)
                }
            })
        }
    }

    function saveMode() {
        var map_str = JSON.stringify(map)
        $.ajax({
            url: '/saveRecord',
            type: 'post',
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    alert("保存成功")
                }
                else {
                    alert("保存失败，请重试！！！")
                }
            },
            error: function (error) {
                console.log(error)
            }
        })
    }
    function selectMode() {
        var flag = confirm("是否保存本局记录")
        if (!flag) {
            location.href = "/home/"
        }
        else {
            // console.log(map)
            var map_str = JSON.stringify(map)
            $.ajax({
                url: '/saveRecord',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    if (data.code == 200) {
                        alert("保存成功")
                        location.href = "/home/"
                    }
                    else {
                        alert("保存失败，请重试！！！")
                    }
                },
                error: function (error) {
                    console.log(error)
                }
            })
        }
    }

    function exit() {
        var flag = confirm("确认退出登录？！")
        if (flag) {
            $.ajax({
                url: '/exit/',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    if (data.code == 200) {
                        console.log(1)
                        location.href = "/"
                    }
                    else {
                        alert("网络连接出错")
                    }
                },
                error: function (error) {
                    console.log(error)
                }
            })
        }


        // location.href = "/"
    }
    var mcanvas = document.querySelector("canvas");
    var ctx = mcanvas.getContext("2d");

    var count = 20;//用来定义棋盘的行数和列数
    var map = new Array(count);

    function init() {
        mcanvas = document.querySelector("canvas");
        ctx = mcanvas.getContext("2d");
        count = 20;
        map = new Array(count);
        isBlack = 1;
        for (var i = 0; i < map.length; i++) {
            map[i] = new Array(count);
            for (var j = 0; j < map[i].length; j++) {
                map[i][j] = 0;
            }
        }

        ctx.strokeStyle = "#000";
        var rectWH = 30; //设置绘制矩形的大小
        for (var i = 0; i < map.length; i++) {
            for (var j = 0; j < map[i].length; j++) {
                ctx.strokeRect(j * rectWH, i * rectWH, rectWH, rectWH);
            }
        }
    }

    for (var i = 0; i < map.length; i++) {
        map[i] = new Array(count);
        for (var j = 0; j < map[i].length; j++) {
            map[i][j] = 0;
        }
    }

    ctx.strokeStyle = "#000";
    var rectWH = 30; //设置绘制矩形的大小
    for (var i = 0; i < map.length; i++) {
        for (var j = 0; j < map[i].length; j++) {
            ctx.strokeRect(j * rectWH, i * rectWH, rectWH, rectWH);
        }
    }

    var isBlack = 1;

    // 绘制棋子
    function drawChess(x, y, color) {
        //修改填充颜色
        ctx.fillStyle = color;
        //画圆---圆心坐标轴（x,y）--半径15--起始点角度0--终点角度为2派---
        ctx.beginPath();
        ctx.save()
        ctx.shadowOffsetX = 2; // 阴影Y轴偏移
        ctx.shadowOffsetY = 2 // 阴影X轴偏移
        ctx.shadowBlur = 3; // 模糊尺寸
        ctx.shadowColor = 'rgba(0, 0, 0, .5)'; // 颜色

        ctx.arc(x, y, 15, 0, Math.PI * 2, false);
        //ctx.fill()填充
        ctx.fill();
        ctx.stroke();
    }
    colorBox = ["#fff", "#000"]

    function Recognation(obj) {
        obj.value = "录音中";
        $.ajax({
            url: '/verify/',
            type: 'post',
            success: function (data) {

                if (data.code != 200) {
                    obj.value = "语音识别";
                    alert(data.msg)
                }
                else {
                    obj.value = "语音识别";
                    // console.log(1);
                    col = data.row;
                    row = data.col;
                    console.log(data)
                    if (map[row][col]) {
                        alert("此处已被落子");
                        return;
                    }
                    drawChess(col * 30, row * 30, colorBox[isBlack]);
                    map[row][col] = 1;
                    $.ajax({
                        url: "/check",
                        type: 'post',
                        dataType: 'json',
                        data: {
                            flag: isBlack,
                            row: row,
                            col: col,
                        },
                        success: function (data) {
                            // console.log(data)
                            if (data.code == 201) {
                                $('.mol-main').css('display', 'block');
                                $('.black').css('display', 'block');
                            }
                            else if (data.code == 202) {
                                $('.mol-main').css('display', 'block');
                                $('.white').css('display', 'block');
                            }
                        },
                        error: function (error) {
                            // console.log(error)
                        }
                    })
                    isBlack ^= 1;
                }
            },
            error: function (error) {
                obj.value = "语音识别";
                console.log(error)
            }
        })
    }
    function playChess(e) {
        // console.log(e)
        var topOffset = mcanvas.offsetTop;
        var leftOffset = mcanvas.offsetLeft;
        // 获取偏移量
        var x = e.clientX - leftOffset;
        var y = e.clientY - topOffset;
        // console.log(x, y)
        var xx = (x - rectWH / 2) / rectWH;
        var yy = (y - rectWH / 2) / rectWH;
        // 获取在棋盘上的位置
        var col = parseInt(xx) + 1;
        var row = parseInt(yy) + 1;
        // console.log(col, row);
        if (map[row][col]) {
            alert("此处已被落子");
            return;
        }
        drawChess(col * 30, row * 30, colorBox[isBlack]);
        map[row][col] = 1;
        $.ajax({
            url: "/check",
            type: 'post',
            dataType: 'json',
            data: {
                flag: isBlack,
                row: row,
                col: col,
            },
            success: function (data) {
                // console.log(data)
                if (data.code == 201) {
                    $('.mol-main').css('display', 'block');
                    $('.black').css('display', 'block');
                }
                else if (data.code == 202) {
                    $('.mol-main').css('display', 'block');
                    $('.white').css('display', 'block');
                }
            },
            error: function (error) {
                // console.log(error)
            }
        })
        isBlack ^= 1;
    }

    function refresh(flag) {
        $.ajax({
            url: '/init',
            type: 'post',
            dataType: 'json',
            data: {
                flag: flag
            },
            success: function (data) {
                if (data.code == 200) {
                    location.href = '/game';
                }
                else {

                    ctx.clearRect(0, 0, 600, 600);
                    init()
                    console.log(map)
                }
            },
            error: function (error) {
                alert('网络连接错误');
            }
        })
    }

    function replay() {
        refresh(2)
    }
    $('.btn').click(function () {
        $('.mol-main').css('display', 'none');
        $('.black').css('display', 'none');
        $('.white').css('display', 'none');
        // location.reload('/game')
        refresh(1)
    });

    window.onbeforeunload = function () {
        refresh(1)
    }
</script>

</html>